<template>
  <div class="dashboard-container">
    <!-- 顶部标题栏 -->
    <div class="dashboard-header">
      <div class="title">智慧停车管理平台</div>
      <div class="weather">
        <i class="el-icon-sunny"></i>
        {{ weather.temp }}°C {{ weather.city }}
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <div class="card">
        <div class="info">
          <div class="value">2,500</div>
          <div class="label">总车位数</div>
          <div class="trend up">2.5% ↑</div>
        </div>
        <div class="icon blue">
          <i class="el-icon-s-grid"></i>
        </div>
      </div>
      <div class="card">
        <div class="info">
          <div class="value">864</div>
          <div class="label">当前空位</div>
          <div class="trend down">1.8% ↓</div>
        </div>
        <div class="icon green">
          <i class="el-icon-s-opportunity"></i>
        </div>
      </div>
      <div class="card">
        <div class="info">
          <div class="value">¥25,630.00</div>
          <div class="label">今日收入</div>
          <div class="trend up">12.5% ↑</div>
        </div>
        <div class="icon orange">
          <i class="el-icon-money"></i>
        </div>
      </div>
      <div class="card">
        <div class="info">
          <div class="value">3,562</div>
          <div class="label">今日车流量</div>
          <div class="trend up">5.2% ↑</div>
        </div>
        <div class="icon purple">
          <i class="el-icon-s-data"></i>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 使用率图表 -->
        <div class="usage-chart panel-card">
          <div class="panel-header">
            <div class="title">停车场使用率</div>
            <div class="tabs">
              <span class="tab active">今日</span>
              <span class="tab">本周</span>
              <span class="tab">本月</span>
            </div>
          </div>
          <div class="chart-container" ref="usageChart"></div>
          <div class="chart-info">
            <div class="info-item">
              <span class="label">平均使用率</span>
              <span class="value">85.6%</span>
            </div>
            <div class="info-item">
              <span class="label">高峰时段</span>
              <span class="value">95.2%</span>
            </div>
            <div class="info-item">
              <span class="label">低谷时段</span>
              <span class="value">45.8%</span>
            </div>
          </div>
        </div>

        <!-- 收入统计 -->
        <div class="income-chart panel-card">
          <div class="panel-header">
            <div class="title">收入统计</div>
            <div class="tabs">
              <span class="tab active">今日</span>
              <span class="tab">本周</span>
              <span class="tab">本月</span>
            </div>
          </div>
          <div class="chart-container" ref="incomeChart"></div>
        </div>
      </div>

      <!-- 中间监控区域 -->
      <div class="center-panel">
        <div class="panel-header">
          <div class="title">停车场实时监控</div>
        </div>
        <div class="video-container">
          <div id="video-container">
            <div v-if="videoError" class="video-fallback">
              <i class="el-icon-video-camera"></i>
              <p>{{ videoErrorMsg }}</p>
              <el-button size="small" type="primary" @click="retryVideo">
                重试
              </el-button>
            </div>
          </div>
        </div>
        <div class="parking-status">
          <div class="status-item" v-for="lot in parkingStatus" :key="lot.name">
            <div class="status-header">
              <span class="name">{{ lot.name }}</span>
              <span class="tag" :class="lot.status">{{ lot.statusText }}</span>
            </div>
            <div class="progress-bar">
              <div class="progress" :style="{
                width: `${(lot.total - lot.available) / lot.total * 100}%`,
                backgroundColor: lot.color
              }"></div>
              <span class="available">空余: {{ lot.available }}/{{ lot.total }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 设备监控 -->
        <div class="monitor-list panel-card">
          <div class="panel-header">
            <div class="title">设备监控</div>
            <i class="el-icon-refresh refresh-btn"></i>
          </div>
          <div class="list-content">
            <div class="monitor-item" v-for="item in monitorList" :key="item.name" :class="item.status">
              <i class="el-icon-video-camera"></i>
              <span class="name">{{ item.name }}</span>
              <span class="status">{{ item.statusText }}</span>
              <span class="time">{{ item.lastUpdate }}</span>
            </div>
          </div>
        </div>

        <!-- 告警信息 -->
        <div class="alert-list panel-card">
          <div class="panel-header">
            <div class="title">告警信息</div>
            <div class="alert-count">
              总计: {{ alertStats.total }} 未处理: {{ alertStats.unhandled }}
            </div>
          </div>
          <div class="list-content">
            <div class="alert-item" v-for="alert in alertList" :key="alert.time" :class="alert.level">
              <div class="time">{{ alert.time }}</div>
              <div class="content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="desc">{{ alert.content }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import CountTo from 'vue-count-to'
import { getToken } from '@/utils/auth'
import EZUIKit from "ezuikit-js"

export default {
  name: 'Index',
  components: {
    CountTo
  },
  data() {
    return {
      currentTime: '',
      timer: null,
      // 天气信息
      weather: {
        temp: 26,
        city: '保定市',
        condition: 'sunny'
      },
      // 日期时间
      dateInfo: {
        date: '',
        time: ''
      },
      // 视图控制
      mapView: '3D',
      currentUsageTab: 'today',
      incomeTimeRange: 'day',

      // 数据总览
      overviewData: [
        {
          title: '总车位数',
          value: 2500,
          icon: 'el-icon-s-grid',
          iconBg: 'linear-gradient(180deg, #1890FF 0%, #77B9FF 100%)',
          trend: 'up',
          rate: '2.5%'
        },
        {
          title: '当前空位',
          value: 864,
          icon: 'el-icon-s-opportunity',
          iconBg: 'linear-gradient(180deg, #52C41A 0%, #95DE64 100%)',
          trend: 'down',
          rate: '1.8%'
        },
        {
          title: '今日收入',
          value: 25630,
          prefix: '¥',
          decimals: 2,
          icon: 'el-icon-money',
          iconBg: 'linear-gradient(180deg, #FAAD14 0%, #FFD666 100%)',
          trend: 'up',
          rate: '12.5%'
        },
        {
          title: '今日车流量',
          value: 3562,
          icon: 'el-icon-s-data',
          iconBg: 'linear-gradient(180deg, #722ED1 0%, #B37FEB 100%)',
          trend: 'up',
          rate: '5.2%'
        }
      ],

      // 使用率标签页
      usageTabs: [
        { key: 'today', name: '今日' },
        { key: 'week', name: '本周' },
        { key: 'month', name: '本月' }
      ],

      // 使用率指标
      usageIndicators: [
        { label: '平均使用率', value: '85.6%', color: '#1890FF' },
        { label: '高峰时段', value: '95.2%', color: '#52C41A' },
        { label: '低谷时段', value: '45.8%', color: '#FAAD14' }
      ],

      // 停车场状态
      parkingStatus: [
        {
          name: 'A区停车场',
          status: 'success',
          statusText: '运行正常',
          usage: 85,
          total: 500,
          available: 75,
          color: '#52C41A'
        },
        {
          name: 'B区停车场',
          status: 'warning',
          statusText: '即将满位',
          usage: 95,
          total: 300,
          available: 15,
          color: '#FAAD14'
        },
        {
          name: 'C区停车场',
          status: 'danger',
          statusText: '已满位',
          usage: 100,
          total: 200,
          available: 0,
          color: '#F5222D'
        }
      ],

      // 监控列表
      monitorList: [
        {
          name: '入口闸机A1',
          status: 'normal',
          statusText: '正常运行',
          lastUpdate: '2分钟前'
        },
        {
          name: '出口闸机B2',
          status: 'warning',
          statusText: '需要维护',
          lastUpdate: '5分钟前'
        },
        {
          name: '监控摄像头C3',
          status: 'error',
          statusText: '离线',
          lastUpdate: '10分钟前'
        }
      ],

      // 告警统计
      alertStats: {
        total: 24,
        unhandled: 5
      },

      // 告警列表
      alertList: [
        {
          time: '10:24:35',
          title: '设备告警',
          content: 'A区入口闸机故障',
          level: 'warning',
          levelText: '警告'
        },
        {
          time: '10:15:22',
          title: '容量告警',
          content: 'B区停车位即将满位',
          level: 'info',
          levelText: '提示'
        },
        {
          time: '10:02:15',
          title: '系统告警',
          content: '系统检测到异常访问',
          level: 'danger',
          levelText: '严重'
        }
      ],
      map: null,
      parkingLots: [
        {
          name: 'A区停车场',
          position: [114.057868, 22.543099],
          total: 500,
          available: 75
        },
        {
          name: 'B区停车场',
          position: [114.059868, 22.543099],
          total: 300,
          available: 15
        },
        {
          name: 'C区停车场',
          position: [114.058868, 22.542099],
          total: 200,
          available: 0
        }
      ],
      eZUIKitPlayer: null,
      accessToken: 'at.7yliog3a10zjrnm320bsq5t6443vutzt-8l08cm00j7-1oje6yu-vjcdnye4d',
      accessUrl: "ezopen://open.ys7.com/BD7300843/1.hd.live",
      dialogImageUrl: '',
      dialogVisible: false,
      token: null,
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/camara/recognition",
      outUploadUrl: process.env.VUE_APP_BASE_API + "/system/camara/outRecognition",
      dialogImageUrl1: '',
      dialogVisible1: false,
      fileList1: [],
      videoError: false,
      videoErrorMsg: ''
    };
  },
  mounted() {
    this.updateTime()
    this.timer = setInterval(this.updateTime, 1000)
    
    // 修改初始化顺序，确保 DOM 已经渲染
    this.$nextTick(() => {
      this.initCharts()
      // 延迟初始化视频播放器
      setTimeout(() => {
        this.initEZUIKitPlayer()
      }, 1000)
    })
  },
  created() {
    this.getTokenUser()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    window.removeEventListener('resize', this.handleResize)
    if (this.eZUIKitPlayer) {
      this.eZUIKitPlayer.destroy()
    }
  },
  methods: {
    // 添加获取萤石云 token 的方法
    async getEZUIKitToken() {
      try {
        // 这里需要调用你的后端接口获取 token
        const response = await this.$http.get('/api/ezuikit/token')
        this.accessToken = response.data.accessToken
      } catch (error) {
        console.error('获取视频 token 失败:', error)
        this.videoError = true
        this.videoErrorMsg = '获取视频授权失败'
      }
    },

    // 修改视频初始化方法
    async initEZUIKitPlayer() {
      try {
        const container = document.getElementById('video-container')
        if (!container) {
          console.warn('视频容器元素不存在')
          return
        }

        // 获取容器的实际尺寸
        const containerWidth = container.clientWidth
        const containerHeight = container.clientHeight

        this.eZUIKitPlayer = new EZUIKit.EZUIKitPlayer({
          id: 'video-container',
          accessToken: this.accessToken,
          url: this.accessUrl,
          header: [],  // 移除顶部工具栏
          footer: [],  // 移除底部工具栏
          width: containerWidth,  // 使用实际宽度
          height: containerHeight, // 使用实际高度
          autoplay: true,
          audio: 1,
          template: 'simple',
          videoStyle: {  // 添加视频样式
            width: '100%',
            height: '100%',
            objectFit: 'fill'  // 使用 fill 填充整个容器
          },
          handleError: (e) => {
            console.error('视频播放器错误:', e)
            this.videoError = true
            this.videoErrorMsg = this.getErrorMessage(e.code)
            
            if (e.code === '10002') {
              this.refreshToken()
            }
          }
        })

        // 添加窗口大小变化监听
        window.addEventListener('resize', this.handleResize)
      } catch (error) {
        console.error('初始化视频播放器失败:', error)
        this.videoError = true
        this.videoErrorMsg = '初始化视频播放器失败'
      }
    },

    // 添加刷新 token 的方法
    async refreshToken() {
      await this.getEZUIKitToken()
      if (this.accessToken) {
        this.retryVideo()
      }
    },

    // 修改重试方法
    async retryVideo() {
      this.videoError = false
      this.videoErrorMsg = ''
      if (this.eZUIKitPlayer) {
        this.eZUIKitPlayer.destroy()
        this.eZUIKitPlayer = null
      }
      await this.initEZUIKitPlayer()
    },

    // 添加错误信息转换方法
    getErrorMessage(code) {
      const errorMessages = {
        '10002': 'AccessToken已过期，正在重新获取',
        '10001': '参数错误',
        '10004': '设备不在线',
        '10005': '设备不存在',
        '10006': '视频质量错误',
        '10007': '视频未开启',
        '10008': '设备接入限制',
        // ... 其他错误码
      }
      return errorMessages[code] || '视频播放出错，请稍后重试'
    },
    getTokenUser() {
      this.token = getToken()
      console.log(this.token, "------->>>>>>>>>>>>>>>>>>>>>>")
    },
    updateTime() {
      const now = new Date()
      this.currentTime = now.toLocaleString()
    },
    initCharts() {
      this.initUsageChart()
      this.initIncomeChart()
    },
    initUsageChart() {
      const chart = echarts.init(this.$refs.usageChart)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: '10%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['00:00', '06:00', '12:00', '18:00', '24:00'],
          axisLine: { lineStyle: { color: '#8392A5' } }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: '#8392A5' } },
          splitLine: { lineStyle: { color: '#061D33' } }
        },
        series: [{
          data: [30, 85, 95, 90, 45],
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: { color: '#00FFFF' },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(0, 255, 255, 0.3)'
            }, {
              offset: 1,
              color: 'rgba(0, 255, 255, 0)'
            }])
          }
        }]
      }
      chart.setOption(option)
    },
    initIncomeChart() {
      const chart = echarts.init(this.$refs.incomeChart)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          top: '10%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          axisLine: { lineStyle: { color: '#8392A5' } }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: '#8392A5' } },
          splitLine: { lineStyle: { color: '#061D33' } }
        },
        series: [{
          data: [15000, 18000, 22000, 20000, 25000, 30000, 28000],
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: '#00FFFF'
            }, {
              offset: 1,
              color: '#0066FF'
            }])
          }
        }]
      }
      chart.setOption(option)
    },
    createInfoWindow(lot) {
      const ratio = lot.available / lot.total
      const content = `
        <div class="map-info-window">
          <h4>${lot.name}</h4>
          <p>总车位：${lot.total}</p>
          <p>空余车位：${lot.available}</p>
          <div class="progress-bar">
            <div class="progress" style="width: ${ratio * 100}%; background: ${this.getStatusColor(ratio)}"></div>
          </div>
        </div>
      `
      return new BMap.InfoWindow(content, {
        width: 200,
        height: 120,
        title: ''
      })
    },

    getStatusColor(ratio) {
      if (ratio > 0.3) return '#67C23A'
      if (ratio > 0.1) return '#E6A23C'
      return '#F56C6C'
    },
    handleUsageTabChange(key) {
      this.currentUsageTab = key
    },
    refreshMonitor() {
      // 实现刷新监控列表的逻辑
    },
    // 添加处理窗口大小变化的方法
    handleResize() {
      if (this.eZUIKitPlayer) {
        const container = document.getElementById('video-container')
        if (container) {
          this.eZUIKitPlayer.resize(container.clientWidth, container.clientHeight)
        }
      }
    }
  },
  watch: {
    mapView: {
      handler: 'handleViewChange'
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  min-height: 100vh;
  padding: 16px;
  background-color: #001529;
  color: #fff;

  // 顶部标题栏
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 50px;
    margin-bottom: 16px;

    .title {
      font-size: 20px;
      color: #00FFFF;
      font-weight: bold;
    }

    .weather {
      display: flex;
      align-items: center;
      gap: 8px;
      
      i {
        color: #FAAD14;
        font-size: 20px;
      }
    }
  }

  // 数据概览卡片
  .overview-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 16px;

    .card {
      background: rgba(0, 21, 41, 0.9);
      border-radius: 4px;
      padding: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border: 1px solid rgba(0, 255, 255, 0.1);

      .info {
        .value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 8px;
          color: #fff;
        }

        .label {
          font-size: 14px;
          color: rgba(255, 255, 255, 0.65);
          margin-bottom: 8px;
        }

        .trend {
          font-size: 12px;
          
          &.up {
            color: #52C41A;
          }
          
          &.down {
            color: #FF4D4F;
          }
        }
      }

      .icon {
        width: 48px;
        height: 48px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;

        i {
          font-size: 24px;
          color: #fff;
        }

        &.blue {
          background: linear-gradient(135deg, #1890FF 0%, #77B9FF 100%);
        }

        &.green {
          background: linear-gradient(135deg, #52C41A 0%, #95DE64 100%);
        }

        &.orange {
          background: linear-gradient(135deg, #FAAD14 0%, #FFD666 100%);
        }

        &.purple {
          background: linear-gradient(135deg, #722ED1 0%, #B37FEB 100%);
        }
      }
    }
  }

  // 主要内容区域
  .main-content {
    display: grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    gap: 16px;
    height: calc(100vh - 150px);

    .panel-card {
      background: rgba(0, 21, 41, 0.9);
      border-radius: 4px;
      border: 1px solid rgba(0, 255, 255, 0.1);
      padding: 16px;
      margin-bottom: 16px;

      .panel-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .title {
          font-size: 16px;
          font-weight: 500;
        }

        .tabs {
          display: flex;
          gap: 8px;

          .tab {
            padding: 4px 12px;
            font-size: 14px;
            cursor: pointer;
            border-radius: 2px;

            &.active {
              background: rgba(0, 255, 255, 0.1);
              color: #00FFFF;
            }
          }
        }
      }
    }

    // 左侧面板
    .left-panel {
      .chart-container {
        height: 280px;
      }

      .chart-info {
        display: flex;
        justify-content: space-around;
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid rgba(255, 255, 255, 0.1);

        .info-item {
          text-align: center;

          .label {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.65);
            margin-bottom: 4px;
          }

          .value {
            font-size: 16px;
            color: #00FFFF;
          }
        }
      }
    }

    // 中间监控区域
    .center-panel {
      .video-container {
        height: calc(100vh - 250px);
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        margin-bottom: 8px;
        overflow: hidden;
        
        #video-container {
          width: 100%;
          height: 100%;
          
          // 视频播放器容器样式
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          
          :deep(.ezuikit-video) {
            width: 100% !important;
            height: 100% !important;
          }
          
          :deep(video) {
            width: 100% !important;
            height: 100% !important;
            object-fit: fill;
          }
        }
      }

      .parking-status {
        height: calc(100% - (100vh - 250px) - 50px);
        overflow-y: auto;
        .status-item {
          margin-bottom: 4px;
          
          .status-header {
            margin-bottom: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .tag {
              padding: 2px 8px;
              border-radius: 2px;
              font-size: 12px;

              &.success {
                background: rgba(82, 196, 26, 0.1);
                color: #52C41A;
              }

              &.warning {
                background: rgba(250, 173, 20, 0.1);
                color: #FAAD14;
              }

              &.danger {
                background: rgba(245, 34, 45, 0.1);
                color: #F5222D;
              }
            }
          }

          .progress-bar {
            height: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            position: relative;

            .progress {
              height: 100%;
              border-radius: 4px;
              transition: width 0.3s ease;
            }

            .available {
              position: absolute;
              right: 0;
              top: -20px;
              font-size: 12px;
              color: rgba(255, 255, 255, 0.65);
            }
          }
        }
      }
    }

    // 右侧面板
    .right-panel {
      .monitor-item {
        display: flex;
        align-items: center;
        padding: 12px;
        margin-bottom: 8px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 4px;

        i {
          margin-right: 8px;
          font-size: 16px;
        }

        .name {
          flex: 1;
        }

        .status {
          margin: 0 8px;
        }

        .time {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.45);
        }

        &.warning {
          border-left: 2px solid #FAAD14;
        }

        &.error {
          border-left: 2px solid #FF4D4F;
        }
      }

      .alert-item {
        padding: 12px;
        margin-bottom: 8px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 4px;

        .time {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.45);
          margin-bottom: 8px;
        }

        .content {
          .alert-title {
            font-weight: 500;
            margin-bottom: 4px;
          }

          .desc {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.65);
          }
        }

        &.warning {
          border-left: 2px solid #FAAD14;
        }

        &.danger {
          border-left: 2px solid #FF4D4F;
        }

        &.info {
          border-left: 2px solid #1890FF;
        }
      }
    }
  }

  .video-fallback {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: rgba(255, 255, 255, 0.65);
    
    i {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    p {
      margin-bottom: 16px;
    }
  }
}
</style>

